package com.itheima.rocketmq.rocketmqdemo.order;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 消息的接受者：顺序消息
 *
 * @description:
 * @author: ycc
 * @time: 2021/3/24
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
//        1.创建消费者consumer，制定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
//        2.指定Nameserver地址
        consumer.setNamesrvAddr("127.0.0.1:9876;127.0.0.1:9877");
//        3.订阅主题Topic和Tag
        consumer.subscribe("OrderTopic", "Order");
        //负载均衡的模式消费
        consumer.setMessageModel(MessageModel.BROADCASTING);
//        4.设置回调函数，处理消息
//        消息消费时，对于一个队列就使用一个线程去处理，保证了消息的顺序性
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext consumeOrderlyContext) {
                for (MessageExt msg:msgs) {
                    System.out.println(Thread.currentThread().getName()+"消费顺序消息："+new String(msg.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
    });
//        5.启动消费者consumer
        consumer.start();
    }
}


